<!--审计日志-->
<template>
    <div>
        <a-row>
            <a-card>
                <p slot="title">
                    日志管理详情
                </p>
                <div class="formSearch">
                    <a-form layout="inline" @keydown.native.enter.prevent="handleSubmit('searchForm')">
                            <a-form-item label="日志类型：">
                                <!--<a-checkbox
                                        :indeterminate="indeterminate"
                                        @change="onCheckAllChange"
                                        :checked="checkAll"
                                >
                                 全部
                                </a-checkbox>-->
                                <a-checkbox-group :options="typeLogList" v-model="checkedLogList" @change="onChangeTypeLog" />
                            </a-form-item>
                        <div style="float: right">
                            <a-form-item label="日志时间：" style="margin-right: 25px;">
                                <a-date-picker
                                        :disabledDate="disabledStartDate"
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        v-model="startValue"
                                        placeholder="开始日期"
                                        style="width: 200px; float: left; min-width: 150px;"
                                />
                                <span style="width: 20px; float: left; text-align: center">-</span>
                                <a-date-picker
                                        :disabledDate="disabledEndDate"
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="结束日期"
                                        v-model="endValue"
                                        style="width: 200px; float: left; min-width: 150px;"
                                />
                            </a-form-item>
                            <a-button type="primary" @click="handleSubmit('searchForm')">查询</a-button>
                            <a-button style="margin-left: 8px" @click="reStore">重置</a-button>
                        </div>
                    </a-form>
                </div>
            </a-card>
            <div style="height: 15px"></div>
            <div class="commonStyle nyContent">
                <div class="table-operator">
                    <a-button  type="primary"  @click="exportAuditLogs">导出日志</a-button>
                </div>
                <a-table :columns="columns" :dataSource="loadData" :rowKey="record => record.id"
                         :rowClassName="rowClassName"
                         :pagination="false">
                        <span slot="index" slot-scope="text, record, index">
                           {{(queryParam.currentPage-1)*queryParam.pageSize+index+1}}
                        </span>
                    <span slot="auditStatus" slot-scope="text"  :style="text !== '1'?'':'color:green'">
                            {{ text === '1' ? '已审计' : '未审计' }}
                        </span>
                    <span slot="auditSort" slot-scope="text" >
                            {{ text === '1' ? '操作日志' : text === '2' ? '通信日志' : '系统日志' }}
                        </span>
                    <span slot="itemParams" slot-scope="text" style="word-break: break-all">
                            <ellipsis :length="18" tooltip :fullString="text"></ellipsis>
                        </span>
                    <span slot="description" slot-scope="text">
                            <ellipsis :length="showTextNum" tooltip :fullString="text"></ellipsis>
                        </span>
                </a-table>
                <Page :totalCount="queryParam.totalCount" :currentPage="page.currentPage" ref="page"
                      :pageSize="page.pageSize"
                      @changePage="changePage" @changePageSize="changePageSize" />
            </div>
        </a-row>
        <iframe id="ifile" style="display: none"></iframe>
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </div>
</template>

<script>
    import {mapState} from 'vuex'
    import Page from 'module/pagination'
    import ellipsis from 'module/ellipsis'
    import moment from 'moment'
    import verify from 'libs/verify'

    export default {
        name: 'audit_logs',
        components: {
            Page,
            ellipsis,
        },
        data () {
            return {
                verify,
                searchErrorMsg:'',
                listT: [],
                typeLogList :[{value: '1', label: '操作日志'},
                    {value: '2', label: '通信日志'},
                    {value: '3', label: '系统日志'}],
                checkedLogList:['1','2','3'],
                indeterminate: true,
                checkAll: false,
                page: {
                    currentPage: 1,
                    pageSize: 10
                },
                array: [ 10, 20, 30, 40 ],
                searchForm: {
                    userName: '',
                    loginIp: '',
                    date: [],
                    itemCode:undefined,
                    operateType: ''
                },
                startValue: null,
                endValue: null,
                columns: [
                    {title: '序号', key: 'index', width: '8%', align: 'center', scopedSlots: {customRender: 'index'}},                   {
                        title: '日志类型',
                        dataIndex: 'auditSort',
                        key: 'auditSort',
                        width: '10%',
                        scopedSlots: {customRender: 'auditSort'}
                    },
                    {title: '子类型', dataIndex: 'itemName', key: 'itemName', width: '10%', scopedSlots: {customRender: 'itemName'}},
                    {title: '操作人', dataIndex: 'userName', key: 'userName', width: '10%'},
                    {title: '时间', dataIndex: 'createTime', key: 'createTime', width: '15%'},
                    {title: '内容', dataIndex: 'description', key: 'description', width: '35%'},
                ],
                showTextNum:30,
                handleAuditLogFlag:false,
                userName:sessionStorage.getItem('user'),
                spinText:'请稍后...',
                spinning:false,
                loadData:[],
                // 查询参数
                queryParam: {
                    pageSize: 10,
                    currentPage: 1,
                    searchText: '',
                    startDate: '',
                    moduleCode: '',
                    operatorName: '',
                    endDate: '',
                    totalCount: 0,
                    responseType:'arraybuffer'
                },
            }
        },
        methods: {
            onChangeTypeLog (checkedList) {
                this.indeterminate = !!checkedList.length && (checkedList.length < this.typeLogList.length)
                this.checkAll = this.checkedLogList.length === this.typeLogList.length
            },
            onCheckAllChange (e) {
                Object.assign(this, {
                    checkedLogList: e.target.checked ? this.typeLogList : [],
                    indeterminate: false,
                    checkAll: e.target.checked,
                })
            },
            emitEmpty (partant,name) {
                this[partant][name] = ''
                if(name=== 'loginIp'){
                    this.searchErrorMsg = ''
                }
                this.init();
            },
            reStore(){
                this.searchForm.userName = ''
                this.searchForm.loginIp = ''
                this.searchForm.itemCode = undefined
                this.searchForm.operateType = undefined
                this.startValue = null
                this.endValue = null
                this.page.currentPage = 1
                this.init();
            },
            /**
             * Function    : disabledStartDate
             * Description : 对结束时间进行限制
             * Input       : startValue
             * Return      : None
             */
            disabledStartDate ( startValue ) {
                const endValue = this.endValue
                if (endValue) {
                    if (moment (startValue).format ('YYYY-MM-DD') === moment (endValue).format ('YYYY-MM-DD')) {
                        return false
                    }
                    return (
                        startValue.valueOf () <
                        moment ()
                            .startOf ('day')
                            .subtract (36, 'months') || startValue.valueOf () > endValue.valueOf ()
                    )
                }
                return (
                    startValue.valueOf () > moment () ||
                    startValue.valueOf () <
                    moment ()
                        .startOf ('day')
                        .subtract (36, 'months')
                )
            },
            /**
             * Function    : disabledEndDate
             * Description : 对结束时间进行限制
             * Input       : endValue
             * Return      : None
             */
            disabledEndDate ( endValue ) {
                const startValue = this.startValue
                if (startValue) {
                    return startValue.valueOf () >= endValue.valueOf () || endValue.valueOf () > moment ()
                }
                return (
                    endValue.valueOf () > moment () ||
                    endValue.valueOf () <
                    moment ()
                        .startOf ('day')
                        .subtract (36, 'months')
                )
            },
            /**
             * Function    : init
             * Description : 初始化加载页面
             * Input       : none
             * Return      : none
             */
            init () {
                this.loadPageData()
            },

            /**
             * Function    : loadPageData
             * Description : 加载页面数据
             * Input       : None
             * Return      : None
             */
            loadPageData () {
                let _this = this
                let searchStartDate = ''
                let searchEndDate = ''
                if (this.endValue === null && this.startValue) {
                    searchStartDate = moment (this.startValue)
                        .format ('YYYY-MM-DD HH:mm:ss')
                        .valueOf ()
                }
                if (this.startValue === null && this.endValue) {
                    searchEndDate = moment (this.endValue)
                        .format ('YYYY-MM-DD HH:mm:ss')
                        .valueOf ()
                }
                if (this.startValue && this.endValue) {
                    searchStartDate = moment (this.startValue)
                        .format ('YYYY-MM-DD HH:mm:ss')
                        .valueOf ()
                    searchEndDate = moment (this.endValue)
                        .format ('YYYY-MM-DD HH:mm:ss')
                        .valueOf ()
                }
                let params = Object.assign ({}, _this.page,
                    {auditSort: _this.checkedLogList.join(',')},
                    {searchStartDate: searchStartDate},
                    {searchEndDate: searchEndDate+'*'},
                )
                _this.$get('/audit/findAuditLogs', params).then(res => {
                    if (res.code === 0) {
                        _this.loadData = res.data.rows;
                        _this.queryParam.totalCount = res.data.total
                    } else {
                        _this.$message.error(res.message)
                    }
                }).catch(res => {
                    _this.$message.error(res.message)
                })
            },

            /**
             * Function    : loadPageData
             * Description : 重新加载加载页面数据
             * Input       : None
             * Return      : None
             */
            reloadPageData () {
                this.page.currentPage = 1
                this.loadPageData ()
            },

            /*查询*/
            handleSubmit (  ) {
                if(this.searchErrorMsg === ''){
                    if(this.checkedLogList.length === 0){
                        this.$message.warning('请选择日志类型')
                        return
                    }
                    this.page.currentPage = 1
                    this.reloadPageData ()
                }
            },
            changePage ( currentPage ) {
                this.page.currentPage = currentPage
                this.loadPageData ()
            },
            /*切换每页条数*/
            changePageSize ( vm ) {
                this.page.pageSize = vm
                this.page.currentPage = 1
                this.loadPageData ()
            },

            /**
             * Function    : rowClassName
             * Description : 篡改记录标红
             * Input       : data 树节点数据
             * Return      : none
             */
            rowClassName ( row ) {
                if (row.flag === '1') {
                    return 'demo-table-info-row-err'
                }
                return ''
            },
            /**
             * Function    : exportAuditLog
             * Description : 导出审计日志
             * Input       : none
             * Return      : none
             */
            exportAuditLogs() {
                let _this = this;
                _this.$confirm ({
                    title: `是否导出已完成审计的日志! `,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        let url = '/audit/exportAuditLogs';
                        _this.spinning = true
                        _this.$get ('audit/exportAuditLogs').then (res => {
                            if (res.code === 0) {
                                _this.downLoadJson(res.data)
                            } else {
                                _this.$message.error (res.message)
                            }
                            _this.spinning = false
                        })
                    }
                })
            },

            downLoadJson(data){
                let blob = ''
                blob =new Blob([this.decodeToArrayBuffer (data.fileContent)])
                let url =URL.createObjectURL(blob)
                let element = document.createElement('a')
                element.style.display = 'none'
                element.href= url
                element.download = data.fileName
                element.click()
            },
            decodeToArrayBuffer(str){
                let bstr = atob(str)
                let length = bstr.length
                let unit8Array = new Uint8Array(length)
                for(let i=0;i<length;i++){
                    unit8Array[i] = bstr.charCodeAt(i)
                }
                return unit8Array.buffer
            },

        },
        created () {
            this.init ()
        },
        mounted(){

        },
        destroyed(){

        }
    }
</script>
<style type="text/css">
    .demo-table-info-row-warn td {
        color: #ff9900;
    }

    .demo-table-info-row-err td {
        color: red;
    }
</style>
